import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import javax.swing.ImageIcon;


/**
 * 
 */
public class VideoStreamServer extends Thread {
	Socket connection = null;
	ServerSocket providerSocket;
	ObjectOutputStream out;
	ObjectInputStream in;

	/**
	 * The constructor sets up a connection to a socket.
	 * @param socket
	 */
	public VideoStreamServer(int port) {
		try {
			providerSocket = new ServerSocket(port);
		} catch (IOException ioexp) {
			System.out.println("Could not create providerSocket: " + ioexp);
		}
	}

	/**
	 */
	public void run() {
		while (true) {
			try {
				System.out.println("Waiting for connection");
				connection = providerSocket.accept();
				System.out.println("Connection received from "
						+ connection.getInetAddress().getHostName() + " on port: " + connection.getLocalPort());

				out = new ObjectOutputStream(connection.getOutputStream());
				in = new ObjectInputStream(connection.getInputStream());
				out.flush();

				CameraListener cam = new CameraListener(this);
				cam.start();
				
				while(true) {
					if (cam.getState() == Thread.State.TERMINATED){
						in.close();
						out.close();
						break;
					} else {
						Thread.sleep(200);
					}
				}
			} catch (IOException ioException) {
				ioException.printStackTrace();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			System.out.println("end of loop.");
		}
	}
	
	/**
	 * Sends images from the camera to the client.
	 * @param image Images from the camera is sent as ImageIcons.
	 * @throws IOException
	 */
	void sendCameraMessage(ImageIcon msg) throws IOException {
		try {
			out.writeObject(msg);
			out.flush();
		} catch (IOException e) {
			throw e;
		}
	}
}
